import base from './base';
import React from 'react';
import * as API_REQ from '../apis/form';
import { _, FieldUtil, WfForm_Public, LinkageControl, GlobalUtil } from './pcPublic';
import * as Util from './formUtil';
import * as continuationProcessUtil from './continuationProcessUtil';
import * as Common from './common';
import * as ForwardPage from './forwardPage';
import { Bubble } from 'weaver-mobile';
import { verifyRemark } from './SignUtil';
import { toJS } from 'mobx'
import * as authTypes from "../constants/secondAuthType";
import {getSecondAuthConfig} from "../apis/secondAuth";
import {filterRequestAction,openQYSAuth} from "../util/secondAuthUtil";
import {saveFlowHandwrite, deleteFlowHandwrite} from "../util/emSDK";
import FlowConfirm from '../components/prompt/FlowConfirm';
import EnsureSubmit from '../components/prompt/EnsureSubmit';
import {QYSUKeyUtil} from '../util/QYSUkeyUtil';
import * as VariableKeys from "../constants/variableKey";

const getLabel = Common.getLabel;
const verifyCustomRegisterEvent = GlobalUtil.verifyCustomRegisterEvent;

//表单提交入口，先校验必填等信息
export const doSubmitForm = (para) => {
    const { actiontype,src,isaffirmance='' } = para;
    const { commonParam } = base.wfGlobalStore;
    const { submitParam } = base.wfOperateStore;
    const { isSubmitDirectNode,lastnodeid,iscreate } = submitParam;
    const isFirstSubmit = iscreate == "1" ? "": "0";
    const params = {...para, ...{isFirstSubmit}};
    if(src == 'submit' || isaffirmance == '1' || src == 'intervenor'){
        //提交前校验自定义函数
        if(!verifyCustomFun(src,isaffirmance)){
            return false;
        }
        const isViewOnly = parseInt(commonParam.isviewonly || 0);
        const isAffirmanceSubmit = parseInt(commonParam.isaffirmance || 0);
        const intervenorright = parseInt(commonParam.intervenorright || 0);
        const needVerify = isViewOnly !== 1 && isAffirmanceSubmit !== 1;
        const submitFn = () =>{
            if(needVerify){
                //校验必须新增明细
                if(!verifyMustAddDetail())
                    return false;
                //校验必填空值范围
                const emptyField = verifyRequiredEmptyField();
                if(emptyField !== ""){
                    Util.showPrompt(emptyField, 1);
                    return false;
                }
            }
            if(isSubmitDirectNode == "1"){
                params.SubmitToNodeid = lastnodeid;
            }
            //流程干预验证必填
            // if(intervenorright > 0){
            //     const result = verifyIntervenorInfo(submitParam);
            //     if(result.type == 0){
            //         Bubble.warning(result.msg,2);
            //         return false;
            //     }
            // }
              //除表单字段外提交表单时的必填校验
            const emptyOtherPramas= verifyRequiredEmptyOtherParams()
              if(emptyOtherPramas.msg) {
                    Util.scrollDom(emptyOtherPramas.dom, true, emptyOtherPramas.msg)
                    return;
              }
            saveSignature();    //保存签章
            doSubmitReady(params);
        }
        //提交校验必填前，支持先执行自定义事件
        needVerify ? verifyCustomRegisterEvent(WfForm_Public.OPER_BEFOREVERIFY, submitFn) : submitFn();
    }else{
        //标题字段放置在模板上且不为只读，则保存校验必填，其它情况后台接收到requestname为空的直接生成默认标题
        const { fieldAttrMap,cellInfo } = base.wfLayoutStore;
        const requestnameViewAttr = fieldAttrMap.has("-1") && fieldAttrMap.get("-1").viewattr || 0;
        if (src === "save" && _.has(cellInfo, ["fieldCellInfo", "-1"]) && requestnameViewAttr > 1 && verifyRequestNameIsEmpty()) {
            Util.showPrompt("field-1", 1);
            return false;
        }
        saveSignature();    //保存签章
        doSubmitReady(params);
    }
}

//校验通过，准备提交
export const doSubmitReady = (params) => {
    const {src,actiontype,isaffirmance,type=""} = params;
    const { commonParam } = base.wfGlobalStore;
    if(verifyRemark(params)){
        //校验自定义拦截事件并判断是否继续提交
        verifyCustomRegisterEvent(params, ()=>{
            //签字意见相关流程，相关文档
            //暂时屏蔽接口
            const { needconfirm ,selectNextFlow, isfreecomfirm} = commonParam;
            const isNeedFlowFreeNodeTips = jundgeNeedFlowFreeNodeTips(src,needconfirm == '1',selectNextFlow);
            if ((actiontype == "remarkOperation" && needconfirm == "1") || isNeedFlowFreeNodeTips) {// || src == "intervenor"
                let content =  getLabel(19990,"确认是否提交?");
                if(isNeedFlowFreeNodeTips) {
                    content = <FlowConfirm/>;
                }
                Common.showConfirm({
                    title: content,
                    okEvent: () => {
                        const { controllBottomBtnDisable } = base.allStores.wfOperateStore;
                        controllBottomBtnDisable(false);
                        doFileUpload(params);
                    },
                    cancelEvent:()=>{
                        const { controlVariableMap } = base.allStores.wfSignInputStore;
                        controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
                    }
                });
            } else if(src == "submit" && isfreecomfirm == "1" && type == ""){
                let content =  getLabel(533507,"自由流程最后一个节点，确认是否提交?");
                Common.showConfirm({
                    title: content,
                    okEvent: () => {
                        const { controllBottomBtnDisable } = base.allStores.wfOperateStore;
                        controllBottomBtnDisable(false);
                        doFileUpload(params);
                    },
                    cancelEvent:()=>{
                        const { controlVariableMap } = base.allStores.wfSignInputStore;
                        controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
                    }
                });
            }else{
                doFileUpload(params);
            }
        });
    }
}

/**
 *  设置“提交到退回节点”的相关参数
 */
const setParam4SubmitDirect = () => {
    const {allStores, wfOperateStore} = base;
    const {secondAuthStore} = allStores;
    const {rightMenu} = wfOperateStore;
    const {lastnodeid} = rightMenu;
    const {isSubmitDirect} = secondAuthStore;
    if (isSubmitDirect == 1) {      //说明是点击了"提交到退回节点"菜单/按钮
        wfOperateStore.changeSubmitParam({SubmitToNodeid: lastnodeid});
    } else {
        wfOperateStore.setSubmitToNodeId();
    }
}

export const doFileUpload = (params) => {
    const {allStores, wfOperateStore} = base;
    const {secondAuthStore} = allStores;
    const {submitParam} = wfOperateStore;
    const {workflowid, nodeid, requestid, f_weaver_belongto_userid, f_weaver_belongto_usertype} = submitParam;

    const {isAuthSuccess, isProtectSuccess} = secondAuthStore;

    //已验证通过或者已数据保护通过
    if (isAuthSuccess == 1 || isProtectSuccess == 1) {
        const {isEnableAuth, secondAuthType, isEnableProtect, protectType, authKey, qysSignWay = 2} = secondAuthStore;

        if (isProtectSuccess != 1 && isEnableProtect == 1) {      //仍然需要数据保护
            if (protectType == authTypes.CA_AUTH|| (protectType == authTypes.QYS && qysSignWay == 1)) {     //CA数据保护
                const isProtectDialog = 1;    //1表示打开的是CA数据保护的窗口
                //先保存表单数据
                let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                wfOperateStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                secondAuthStore.setCAAuthData({isProtectDialog});
                secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                doFileUpload0(params);
                return;
            }else if(protectType == authTypes.QYS && qysSignWay == 2){     //契约锁数据保护
                const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                secondAuthStore.setCAAuthData({isProtectDialog});

                //弹出契约锁验证或者数据保护的窗口
                openQYSAuth();
                return;
            }
        }

        //能运行到这里，说明已经做完了数据保护
        if (isEnableProtect == 1) {
            if (protectType == authTypes.CA_AUTH || (qysSignWay == 1 && protectType == authTypes.QYS)) {
                wfOperateStore.changeSubmitParam({authKey, isProtectSuccess});
            }
        }

        //契约锁数据保护或者认证
        if (protectType == authTypes.QYS || secondAuthType == authTypes.QYS) {
            const {authResult} = secondAuthStore;
            const {qysSealId, qysSealImg, qysCertDetails} = authResult;
            wfOperateStore.changeSubmitParam({qysSealId, qysSealImg, qysCertDetails});
        }

        wfOperateStore.changeSubmitParam({protectType, qysSignWay, secondAuthType, isAuthSuccess});

        //设置“提交到退回节点”的相关参数
        const {src, actiontype} = params;
        if (actiontype == "requestOperation" && src == "submit") {
            setParam4SubmitDirect();
        }

        //只验证签字意见
        verifyRemark({needCheck:true, needPrompt:false});
        doFileUpload0(params);
    } else {     //没有做过数据验证
        const {src} = params;
        getSecondAuthConfig({workflowid, nodeid, requestid,src}).then(data => {
            //每个参数的数据都设置一个默认值，避免节点删除，取不到配置信息时会导致错误的问题
            const {isEnableAuth = 0, secondAuthType = 0, isEnableProtect = 0, protectType = 0,qysSignWay = 2, authOperations = [], signUrl = ""} = data;
            if (filterRequestAction(params, submitParam, authOperations)) {       //判断流程的操作类型(提交、保存、退回等)是否需要二次提交验证
                secondAuthStore.setDialogData({isEnableAuth, secondAuthType, isEnableProtect, protectType,qysSignWay, signUrl});
                //如果开启了数据保护或者数据验证，但是没有不是在EM app上执行操作，就提示
                if(!secondAuthStore.canDoSecondAuth()){
                    return;
                }
                if (isEnableAuth == 1) {        //二次认证
                    secondAuthStore.setCallbackParam(params);

                    if (isEnableProtect == 1 &&
                        ((secondAuthType == authTypes.CA_AUTH && protectType == authTypes.CA_AUTH)
                        || (secondAuthType == authTypes.QYS && protectType == authTypes.QYS && qysSignWay == 1))) {    //如果同时还是CA数据保护
                        const isProtectDialog = 10;    //10表示打开的是 CA二次认证 + CA数据保护的窗口
                        //先保存流程表单的数据
                        let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                        wfOperateStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                        secondAuthStore.setCAAuthData({isProtectDialog});
                        secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                        doFileUpload0(params);
                        return;
                    } else if (secondAuthType == authTypes.QYS && isEnableProtect == 1 && protectType == authTypes.QYS && qysSignWay == 2) {    //如果同时还是契约锁数据保护
                        const isProtectDialog = 10;    //10表示打开的是 契约锁二次认证 + 契约锁数据保护的窗口
                        secondAuthStore.setCAAuthData({isProtectDialog});
                        secondAuthStore.setCallbackFunc(doFileUpload);

                        //弹出契约锁验证或者数据保护的窗口
                        openQYSAuth();
                    } else {
                        if (secondAuthType == authTypes.CA_AUTH||(secondAuthType == authTypes.QYS&&qysSignWay == 1)) {
                            //验证时，sourcestr的值为空，但是ca认证时这个值又是必须的，因此初始化一个随机值
                            const {authKey, sourcestr = Math.random()} = data;
                            secondAuthStore.setCAAuthData({authKey, sourcestr});
                        }
                        secondAuthStore.setCallbackFunc(doFileUpload);
                        //弹出验证或者数据保护的窗口
                        if (secondAuthType == authTypes.QYS&&qysSignWay == 2) {      //契约锁二次认证
                            openQYSAuth();
                        } else if(secondAuthType == authTypes.QYS&&qysSignWay == 1){
                            QYSUKeyUtil.showSignWin(secondAuthStore);
                        }else{        //CA二次认证
                            secondAuthStore.controlDialogVisible(authTypes.SECOND_AUTH_DIALOG, true);
                        }
                    }
                } else {     //没有开启二次认证
                    if (isEnableProtect == 1) {
                        secondAuthStore.setCallbackParam(params);

                        //目前数据保护的方式只有2种：CA保护，契约锁保护
                        if (protectType == authTypes.CA_AUTH||(protectType == authTypes.QYS&&qysSignWay == 1)) {       //CA认证的方式
                            const isProtectDialog = 1;    //1表示打开的是CA数据保护的窗口
                            //先保存流程表单的数据
                            let cakey = requestid + "_" + f_weaver_belongto_userid + "_" + f_weaver_belongto_usertype + "_" + new Date().getTime();
                            wfOperateStore.changeSubmitParam({isCAAuth: 1, CAKey: cakey});
                            secondAuthStore.setCAAuthData({isProtectDialog});
                            secondAuthStore.saveDataToStorage(cakey);   //将已经处理过的数据，存入localStorage
                            doFileUpload0(params);
                            return;
                        } else if (protectType == authTypes.QYS&&qysSignWay == 2) {        //契约锁保护也需要弹出窗口
                            const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                            secondAuthStore.setCAAuthData({isProtectDialog});

                            secondAuthStore.setCallbackFunc(doFileUpload);
                            //弹出契约锁验证或者数据保护的窗口
                            openQYSAuth();
                        }
                    } else {
                        doFileUpload0(params);
                    }
                }
            } else {
                doFileUpload0(params);
            }
        });
    }
}

//上传附件，上传完成后提交表单
const doFileUpload0 = (params) =>{
    // const { wfGlobalStore,wfLayoutStore } = base;
    // wfGlobalStore.setLoading(true);
    // if(typeof(window.startUploadAll) == "function"){
    //     window.startUploadAll();	//上传附件
    // }
    // let timer = setInterval(()=>{
    //     //检测附件是否上传完成
    //     const { mainData,fieldAttrMap } = wfLayoutStore;
    //     let uploadArr = new Array();
    //     mainData.forEach((fieldObj,k) =>{
    //         const fieldid = k.substring(5);
    //         if(fieldAttrMap.has(fieldid)) {
    //             const fieldAttr = fieldAttrMap.get(fieldid);
    //             const { variable } = fieldObj;
    //             if(fieldAttr.htmltype === 6 && variable.has("fileUploadStatus"))
    //                 uploadArr.push(variable.get("fileUploadStatus"));
    //         }
    //     });
    //     const failedArr = uploadArr.filter(o=> o !== "uploaded");
    //     //处理上传失败的情况
    //     if(failedArr.length === 0){
    //         doSubmitPost(params);
    //         clearInterval(timer);
    //     }
    // },100);
    const {controllBottomBtnDisable,btnDisabled} = base.allStores.wfOperateStore;
    const { locatedBeforeSubmit, editFieldIds = [] } = base.allStores.wfLocationMap;
    if(btnDisabled) {
        return;
    }
    controllBottomBtnDisable(true);
    if(editFieldIds.length > 0 && (params.src == 'submit' || params.src == 'reject' || params.isaffirmance == 1 || params.actiontype == 'remarkOperation')) {
        //提交前再次定位
        locatedBeforeSubmit((appendParams) => {
            doSubmitPost({...params, ...appendParams});
        });
    } else {
    doSubmitPost(params);
    }
}

//表单提交请求至后台 
export const doSubmitPost = (params) =>{
    LinkageControl.verifyLinkageFinished(() =>{
        const { src,actiontype,saveCallFun } = params;
        delete params['saveCallFun'];
        const { wfGlobalStore,wfOperateStore, allStores } = base;
        const { wfSignInputStore } = allStores;
        const { commonParam } = wfGlobalStore;
        const { submitParam,rightMenu,changeSubmitParam } = wfOperateStore;
        const { signatureAttributesStr, signatureSecretKey, selectNextFlow} = commonParam;
        const { isFree } = rightMenu;
        const formDatas = generateFormData();   //表单字段参数
        const freeNodeInfo  = generateFreeNodeData(isFree);         //自由流程参数
        const allParams = { ...submitParam, selectNextFlow, ...params, ...formDatas, ...{src,signatureAttributesStr,signatureSecretKey}, ...freeNodeInfo};
        wfGlobalStore.setLoading(true);
        const {controllBottomBtnDisable} = base.allStores.wfOperateStore;
        let showEnsureSubmitDialog  = false; //流程提交二次确认弹框显示
        API_REQ.reqOperate(actiontype, allParams).then(result=>{
            const {data,errorInfo = '系统错误，请联系管理员！',errorType = ''} = result;
            if(data) {

                const {type, resultInfo} = data;

                //流程连续处理，保存表单后切换流程
                if(params.continuationSwitchType && src == "save" && type === "SUCCESS") {
                    continuationProcessUtil.switchRequest(params.continuationSwitchType);
                    return;
                }

                //更新操作信息
                changeSubmitParam(data.submitParams);
                if (type === "FAILD" && params.src !== "intervenor") {
                    Util.reloadRequestPage(resultInfo, false);
                } else if (type === "FAILD" && params.src === "intervenor") {
                    //什么都不做
                    Bubble.error(getLabel(384137, '操作失败'));
                } else if (type === "SUCCESS") {
                    const {isaffirmance = '', isNextNodeOperator = false, isShowChart = '0', isCAAuth = '0', needRemind = false,pcUrl = '',mobileUrl=''} = resultInfo;
                    const {wfNextNodeOperator, wfGlobalStore, allStores} = base;
                    const {baseParam, commonParam} = wfGlobalStore;
                    const requestidNew = parseInt(submitParam.requestid) <= 0 ? resultInfo.requestid : submitParam.requestid;
                    //保存成功后，再保存手写签批痕迹,保存以外的其他操作，删除本地流程签批
                    if (src === 'save' && submitParam.requestid != -1) {
                        saveFlowHandwrite(submitParam.requestid)
                    } else if (src === "submit") {
                        deleteFlowHandwrite(submitParam.requestid)
                    }
                    const judgeShowRemind = (needShow = false, callback) => {
                        if (needShow) {   //弹窗选择提醒人
                            window.historyRoute.push({
                                pathname: "/req/reminderConfirm",
                                params: {requestId: requestidNew, workflowId: baseParam.workflowid, submitType: src},
                                callback: callback
                            });
                        } else {
                            callback();
                        }
                    }
                    //保存成功后，触发子流程
                    if (actiontype == "requestOperation" && src == "save" && saveCallFun) {
                        saveCallFun();
                        return;
                    }
                    if (resultInfo.selectNextFlow == "1" && (src != "save" || resultInfo.isaffirmance == "1") && resultInfo.isaffirmanceSrc != 'reject' && src != 'reject') {
                        //用户选择下一节点流转 lijia
                        if (allParams.nodeid && data.messageInfo && (allParams.nodeid != data.messageInfo.nodeIds || data.messageInfo.hasPassThisNode) && !allParams.SubmitToNodeid) {
                            const {wfNextNodeOperator} = allStores;
                            wfNextNodeOperator.setdefaultnodeids(data.messageInfo.nodeIds);
                            wfNextNodeOperator.setDoSubmitReady(doSubmitForm);
                            wfNextNodeOperator.setCancelFunc(() => {
                                Util.reloadRequestPage({requestid: requestidNew}, false);
                            })
                            window.historyRoute.push({
                                pathname: "/req/nextNodeOperator",
                                params: {...baseParam, ...commonParam, ...{requestid: requestidNew}},
                            });
                        } else {//能流转到下一节点才弹出流转设置弹框
                            wfGlobalStore.setLoading(false);
                            controllBottomBtnDisable(false);
                            doSubmitReady({src: "submit", actiontype: "requestOperation", selectNextFlow: '1'});
                        }
                    } else if ( resultInfo.isaffirmance != "1" && (actiontype == "requestOperation" && src == "save") || isNextNodeOperator || isCAAuth == "1") {//提交需确认
                        judgeShowRemind(isNextNodeOperator && needRemind, () => {
                            Util.reloadRequestPage(resultInfo, false);
                        });
                    }  else if (resultInfo.isaffirmance == "1" && (actiontype == "requestOperation" && src == "save")) {
                        showEnsureSubitDialog(data)
                      showEnsureSubmitDialog = true;
                    } else if (needRemind) {
                        judgeShowRemind(needRemind, () => {
                            if (isShowChart == '1'&&pcUrl!='') {
                                let params = {
                                    pcUrl,
                                    mobileUrl,
                                    isShowChart,
                                    ...baseParam, ...commonParam,
                                    requestid: requestidNew
                                };
                                window.historyRoute.push({
                                    pathname: "/req/easyPicture",
                                    params: {...baseParam, ...commonParam, ...params},
                                });
                            } else if (isShowChart == '3') {
                                Util.reloadRequestPage(resultInfo, false);
                            } else {
                                if (allParams.src == "intervenor") {
                                    Bubble.success(getLabel(504641, "干预成功"), 2);
                                    setTimeout(() => {
                                        Util.returnSourcePage({source: "intervenor"});
                                    }, 2000)
                                } else {
                                    Util.returnSourcePage({
                                        source: "submit",
                                    });
                                }
                            }
                        });
                    }else if(isShowChart === "3"){
                        Util.reloadRequestPage(resultInfo, false);
                    }else if(isShowChart === "1"&&pcUrl!=''){
                        let params = {
                            pcUrl,
                            mobileUrl,
                            isShowChart,
                            ...baseParam, ...commonParam,
                            requestid: requestidNew
                        };
                        window.historyRoute.push({
                            pathname: "/req/easyPicture",
                            params: {...baseParam, ...commonParam, ...params},
                        });
                    }else{
                        if (allParams.src == "intervenor") {
                            Bubble.success(getLabel(504641, "干预成功"), 2);
                            setTimeout(() => {
                                Util.returnSourcePage({source: "intervenor"});
                            }, 2000)
                        } else {
                            Util.returnSourcePage({
                                source: "submit",
                            });
                        }
                    }
                } else if (type === "SEND_PAGE") { //无权限
                    window.location.href = data.sendPage;
                } else if (type === "WF_LINK_TIP") { //出口提示
                    Common.showConfirm({
                        title: resultInfo.msgcontent,
                        okEvent: () => {
                            changeSubmitParam({isFirstSubmit: 1, requestid: resultInfo.requestid});
                            doSubmitReady({src, actiontype: "requestOperation", type});
                        },
                        cancelEvent:()=>{
                            const { controlVariableMap } = wfSignInputStore;
                            controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
                        }
                    });
                } else if (type === "R_CHROSE_OPERATOR") {    //异常处理选择操作者
                    const {needChooseOperator, ehnextnodeid} = resultInfo;
                    if (needChooseOperator == "y")
                        chooseExceptionOperator(ehnextnodeid);
                } else if (type === "DELETE") {
                    Bubble.success(getLabel(502230, "删除成功"), 2);
                    Util.returnSourcePage({source: "delete",msgSubmitFormAction : commonParam.msgSubmitFormAction});
                } else if (type === "ASYNC_SUBMIT") {
                    Util.returnSourcePage({source: "submit"});
                }
            }
            wfGlobalStore.setLoading(false);
            if( showEnsureSubmitDialog ) {
              showEnsureSubmitDialog = false;
              controllBottomBtnDisable(true);  //流程提交二次确认弹框显示的情况下，表单底部操作按钮禁用
            } else {
              controllBottomBtnDisable(false);  
            }
        });
    });
}

//提交需确认弹框
const showEnsureSubitDialog = (data) =>{
    const { wfGlobalStore, allStores} = base;
    let srcSource =   data.resultInfo && data.resultInfo.isaffirmanceSrc || 'submit';
    wfGlobalStore.commonParam.requestid = data.submitParams.requestid;
    base.smartGuessStore.initParams({ ...wfGlobalStore.commonParam,...data.submitParams});
    base.smartGuessStore.setPromptInfo(data.messageInfo);
    base.smartGuessStore.setSubmitParam(data.submitParams);
    let showDialog = () => {
        let ensureSubmitDialog = Common.showConfirm({
            title: getLabel(22161, '确定要提交吗？'),
            content: <EnsureSubmit/>,
            wrapClassName: 'ensure-submit-modal',
            okEvent: () => {
            doSubmitForm({actiontype:"requestOperation", src:srcSource});
            },
            cancelEvent:()=>{
                const { controlVariableMap } = allStores.wfSignInputStore;
                controlVariableMap(VariableKeys.CURR_OPERATE_TYPE,{});
            }
        })
        base.smartGuessStore.setDialogClose(ensureSubmitDialog);
    }
    updateDetailKeyId(showDialog,data.insertDetailDatasInfo);
}

//更新明细表的keyid
const updateDetailKeyId = (callback,dateilKeyDatas) => {
    const { wfGlobalStore, wfLayoutStore } = base;
    const { commonParam={} } = wfGlobalStore;
    const { detailMap } = wfLayoutStore;
    let detailmark = "";
    detailMap.forEach((obj,v) =>{
        detailmark += v+",";
    });
    if(detailmark !== "") {
        detailmark = detailmark.substring(0, detailmark.length-1);
    }

    let needUpdate = commonParam.iscreate == '1';
    if(detailmark !== "" && !needUpdate) {
        needUpdate  = detailmark.split(",").some(detailMark =>{
            const detailObj = detailMap.get(detailMark);
            const { indexnum } = detailObj;
            const rowInfo = toJS(detailObj.rowInfo);
            return indexnum > 0 && Object.keys(rowInfo).some(rowkey =>{
                const rowData = rowInfo[rowkey];
                return !rowData.keyid || rowData.keyid <= 0;
            });
        });
    }

    if(detailmark !== "" && needUpdate) {

        let shortRowKey = (a,b) => {
            return a.substring(4) - b.substring(4);
        }

        let existKeys = [];

        detailMap.forEach((obj, detailKey) => {
            const idList = dateilKeyDatas[detailKey];
            const detailObj = detailMap.get(detailKey);
            const { indexnum } = detailObj;
            const rowInfo = toJS(detailObj.rowInfo);
            indexnum > 0 && Object.keys(rowInfo).sort(shortRowKey).map((rowkey, index) =>{
                const rowData = rowInfo[rowkey];
                if((!rowData.keyid || rowData.keyid == 0) && existKeys.indexOf(rowData.keyid) == -1) {
                    wfLayoutStore.detailMap.get(detailKey).rowInfo.get(rowkey).set('keyid', idList[(index-existKeys.length)]);
                } else {
                    existKeys.push(rowData.keyid);
                }
            });
        })

        callback();
    } else {
        callback();
    }
}


const chooseExceptionOperator = (ehnextnodeid) =>{
    const { wfGlobalStore } = base;
    const { commonParam={}, secLevelInfo={} } = wfGlobalStore;
    window.historyRoute.push({
        pathname: "/req/ehOperator",
        params: {ehnextnodeid:ehnextnodeid, requestid : commonParam.requestid, secLevel : secLevelInfo.secLevel},
        callback: (ehparams) =>{
            const { changeSubmitParam } = base.wfOperateStore;
            changeSubmitParam(ehparams);
            doSubmitReady({src:"submit", actiontype:"requestOperation"});
        }
    });
}
window.chooseExceptionOperator = chooseExceptionOperator;

//校验自定义函数
export const verifyCustomFun = (src,isaffirmance) => {
	//post前调用公共方法
	let ischeckok = true;
	if(src === 'submit' || isaffirmance === '1'){
		if(typeof(window.checkCustomize) == "function"){
            ischeckok = window.checkCustomize();
		}
	}
	return ischeckok;
}

//干预提交验证
export const verifyIntervenorInfo = (submitParam) =>{
	const {submitNodeId = '',Intervenorid = ''} = submitParam;
	let result = {type:1};
	if(_.trim(submitNodeId).length === 0){
	    result.type = 0;
	    result.msg = getLabel(386188,'"流转至节点"未填写');
	}
	if(_.trim(Intervenorid).length === 0){
		result.type = 0;
		result.msg = getLabel(386189,'"流转至节点操作者"未填写');
	}
	return result;
}

//提交校验必须新增明细
export const verifyMustAddDetail = () =>{
    let needAddDetailMark = "";
    const { detailMap } = base.wfLayoutStore;
    detailMap.forEach((detailObj,detailMark) =>{
        const { attr,rowInfoArr } = detailObj;
        if(attr.isneed === 1 && rowInfoArr.length === 0 && needAddDetailMark === ""){
            const detailIndex = parseInt(detailMark.replace("detail_", "")) - 1;
            const detailLocTr = window.jQuery("#oTable"+detailIndex).closest(".wf-detail").closest("tr");
            if(detailLocTr.length > 0 && detailLocTr.css("display") !== "none"){
                needAddDetailMark = detailMark;
                return false;
            }
        }
    });
    if(needAddDetailMark !== ""){
        Util.showPrompt(needAddDetailMark, 3);
        return false;
    }else
        return true;
}

 //除表单字段外提交表单时的必填校验
 export const verifyRequiredEmptyOtherParams = () =>{
    const { wfGlobalStore, wfOperateStore } = base;
    const { commonParam } = wfGlobalStore;
    const { submitParam } = wfOperateStore;
    const { showFreeWfSimpleCom } = commonParam;
    let obj={};
    if(showFreeWfSimpleCom != 0){
        const { wfFreeWorkflowSimple } = base.allStores;
        const {conditionData={}}=wfFreeWorkflowSimple;
        if(submitParam.isToNewAddSign < 2 && submitParam.operatorids == "" && conditionData.hasOwnProperty("default_prefix")){
            obj.scrollDom = '.wf-req-freeWorkflowSimple';
            obj.msg = getLabel(512971, "请选择节点操作者");
        }
    }
    return obj;
}

//提交校验字段必填范围
export const verifyRequiredEmptyField = () =>{
    let emptyField = "";
    const { fieldAttrMap,cellInfo,mainData,detailMap,variableMap } = base.wfLayoutStore;
    //联动隐藏行中的其它字段，忽略校验必填
    let ignoreVerifyRange = [];
    const reg = /^field\d+_viewAttr$/;
    variableMap.forEach((v,k) =>{
        if(reg.test(k)){
            const fieldid = k.match(/\d+/)[0];
            if(v === 4){    //隐藏内容
                ignoreVerifyRange.push(fieldid);
            }else if(v === 5){  //隐藏行
                const rowMark = _.get(cellInfo, ["fieldCellInfo", fieldid, "rowMark"]);
                rowMark && rowMark.split(",").forEach(item =>{
                    const rowFields = _.get(cellInfo, ["mainRowFields", item]) || [];
                    ignoreVerifyRange = ignoreVerifyRange.concat(rowFields);
                });
            }
        }
    });
    //计算明细需要校验的行号
    let detailVerifyRowIndexStr = {};
    detailMap.forEach((detailObj,detailMark) =>{
        const { attr,rowInfo } = detailObj;
        let rowIndexStr = "";
        rowInfo.forEach((v,k) =>{
            const keyid = v.has("keyid") ? parseInt(v.get("keyid")) : -1;
            if(keyid <= 0 || (keyid > 0 && attr.isedit === 1))
                rowIndexStr += k.substring(4) + ",";
        });
        if(rowIndexStr !== "")
            rowIndexStr = rowIndexStr.substring(0, rowIndexStr.length-1);
        detailVerifyRowIndexStr[detailMark] = rowIndexStr;
    });
    //校验必填字段的范围
    let verifyRange = [];
    const fieldCellInfo = cellInfo.fieldCellInfo || {};
    _.forIn(fieldCellInfo, (v,fieldid) =>{
        const orderid = v.orderid || 0;
        if(!fieldAttrMap.has(fieldid))
            return true;
        const fieldAttr = fieldAttrMap.get(fieldid);
        const isDetail = fieldAttr.isDetail;
        const tableMark = fieldAttr.tableMark;
        const { htmltype,detailtype } = fieldAttr;
        //Check框等类型、联动隐藏的行字段不校验必填
        if(htmltype === 4 || htmltype === 7 || htmltype === 8 || htmltype === 9 || fieldid === "-9"
            || (!isDetail && _.indexOf(ignoreVerifyRange,fieldid) > -1))
            return "";
        //附件上传未设置固定目录的不校验必填
        if(htmltype === 6 && _.get(fieldAttr, ["fileattr","catelogType"]) === 0 && _.trim(_.get(fieldAttr, ["fileattr","docCategory"])) === "")
            return "";
        //主字段，API隐藏的区域内字段不校验必填，兼容E8
        if(!isDetail && window.jQuery(`.field${fieldid}_swapDiv`).length > 0){
            const fieldSwapObj = window.jQuery(`.field${fieldid}_swapDiv`);
            if(fieldSwapObj.is(".filter_required") || fieldSwapObj.closest("tr").is(".filter_required"))
                return "";
        }
        const rowIndexStr = isDetail ? detailVerifyRowIndexStr[tableMark] : "-1";
        !!rowIndexStr && rowIndexStr.split(",").map(rowIndex =>{
            const fieldMark = isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
            const fieldObj = FieldUtil.getFieldObj(fieldMark, tableMark);
            const { variable } = fieldObj;
            let needVerify = false;
            if(variable.has("viewAttr") && variable.get("viewAttr") > 0){    //显示属性联动控制必填
                needVerify = variable.get("viewAttr") === 3;
            }else{
                needVerify = fieldAttr.viewattr === 3;
            }
            if(needVerify)
                verifyRange.push({fieldid, rowIndex, orderid:(orderid+parseInt(isDetail ? rowIndex : 0)), fieldObj, fieldAttr});
        });
    });
    verifyRange = verifyRange.sort((a,b) =>{
        return a.orderid-b.orderid;
    });
    //根据范围依次校验值是否填写
    for(let i=0; i<verifyRange.length; i++){
        const { fieldid,rowIndex,fieldObj,fieldAttr } = verifyRange[i];
        const { htmltype,detailtype,isDetail } = fieldAttr;
        const fieldMark = isDetail ? `field${fieldid}_${rowIndex}` : `field${fieldid}`;
        let fieldValue = fieldObj.value;
        if(fieldid == -4 || (htmltype === 2 && detailtype === 2)){ //富文本
        	fieldValue =  fieldValue.replace(/<p>/ig,'').replace(/<\/p>/ig,'').replace(/ /ig, "").replace(/&nbsp;/ig, "").replace(/<br \/>/ig,"");
        }
        fieldValue = _.trim(fieldValue);
        if(fieldValue === ""){
            emptyField = fieldMark;
            break;
        }
    }
    return emptyField;
}

//验证流程标题必填
export const verifyRequestNameIsEmpty = () =>{
    const { mainData } = base.wfLayoutStore;
    const fieldValue = mainData.has("field-1") ? mainData.get("field-1").value : "";
    return _.trim(fieldValue) === "";
}

//提交保存签章(待实现)
const saveSignature = () => {
    const { submitParam } = base.wfOperateStore;
    const { isFormSignature,isHideInput } = submitParam;
	if(isFormSignature == "1" && isHideInput != "1" && typeof window.SaveSignature == "function") {
        const flag = window.SaveSignature();
	}
}

//生成表单字段提交参数
export const generateFormData = () =>{
    let datas = {};
    const { fieldAttrMap,mainData,detailMap,existChangeRange } = base.wfLayoutStore;
    datas.existChangeRange = existChangeRange.join(",");
    mainData.forEach((fieldObj,k) =>{
        const fieldname = FieldUtil.convertSystemFieldName(k);
        const fieldid = k.substring(5);
        addCustomizeBrowserNames(datas,fieldAttrMap,fieldid,fieldObj,-1);
        datas[fieldname] = fieldObj.value;
        //多人力分组信息
        if(fieldAttrMap.has(k.substring(5))) {
            const fieldAttr = fieldAttrMap.get(k.substring(5));
            if (fieldAttr.htmltype === 3 && fieldAttr.detailtype === 17) {
                const groupInfo = FieldUtil.buildMultiUserGroupInfo(fieldObj);
                const groupnum = groupInfo.groupnum;
                for (let i = 0; i < groupnum; i++) {
                    if (`group_${i}` in groupInfo)
                        datas[`${fieldname}group${i}`] = groupInfo[`group_${i}`];
                }
                datas[`${fieldname}groupnum`] = groupnum;
            }
        }
    });
    detailMap.forEach((detailObj,detailMark) =>{
        const detailIndex = parseInt(detailMark.substring(7)) - 1;
        const { indexnum,deldtlid,detailData,rowInfo,fieldInfo } = detailObj;
        let submitidArr = new Array();
        let nodesnum = 0;
        rowInfo.forEach((info,rowKey) =>{
            nodesnum++;
            const rowIndex = rowKey.substring(4);
            submitidArr.push(rowIndex);
            if(info.has("keyid"))
                datas[`dtl_id_${detailIndex}_${rowIndex}`] = info.get("keyid");
            _.forIn(fieldInfo, (v,fieldid) =>{
                const fieldMark = `field${fieldid}_${rowIndex}`;
                if(detailData.has(fieldMark)) {
                    const fieldObj  = detailData.get(fieldMark);
                    datas[fieldMark] = fieldObj.value;
                    addCustomizeBrowserNames(datas,fieldAttrMap,fieldid,fieldObj,rowIndex);
                }
            });
        });
        datas[`nodesnum${detailIndex}`] = nodesnum;
        datas[`indexnum${detailIndex}`] = indexnum;
        let submitdtlid = "";
        submitidArr.sort((a,b) =>{
            return parseInt(a) - parseInt(b);
        }).map(_id =>{
            submitdtlid += _id+",";
        });
        datas[`submitdtlid${detailIndex}`] = submitdtlid;
        datas[`deldtlid${detailIndex}`] = deldtlid;
    });
    return datas;
}

const addCustomizeBrowserNames = (datas = {},fieldAttrMap,fieldid,fieldObj,rowIndex = -1) =>{
    const fieldAttr = fieldAttrMap.get(fieldid);
    if(fieldAttr) {
        if(fieldAttr.htmltype === 3 && (fieldAttr.detailtype === 161 || fieldAttr.detailtype === 162)){
            const specialobj = fieldObj.specialobj || [];
            if(specialobj && specialobj.length > 0) {
                const namesplitstr = '##~~@@~~##';
                const fieldnameArr = [];
                specialobj.forEach((vObj,index)=>{
                    fieldnameArr.push(vObj.name);
            })
                let key  = `field${fieldid}name`;
                if(rowIndex > -1) key = `field${fieldid}_${rowIndex}name`;
                datas[key] = fieldnameArr.join(namesplitstr);
            }
        }
    }
}

//生成自由流程提交参数
export const generateFreeNodeData = (isFree)=>{
	let freeNodeInfo  = {};
	if(isFree == "1"){
		// jQuery('.freeNode').find('input').map((o,k)=>{
		// 	freeNodeInfo[k.name] = k.value;
		// });
	}
	return freeNodeInfo;
}

const jundgeNeedFlowFreeNodeTips = (src,needconfirm = false,selectNextFlow) =>{
    if(selectNextFlow == '1') return false;
    let needTips = (src == 'submit' && !needconfirm) || (src == 'save' && needconfirm);
    if(!needTips) return false;
    const {commonParam,variableMap} = base.wfGlobalStore;
    let {isNeedFlowFreeNodeTips = false} = commonParam;

    const {submitParam} = base.wfOperateStore;
    let {SubmitToNodeid = ''} = submitParam;

    //提交至退回节点
    if(SubmitToNodeid > 0 || SubmitToNodeid < -1) {
        return false;
    }

    //流程图保存后返回的实时参数
    if(variableMap.has('isNeedFlowFreeNodeTips')) {
        isNeedFlowFreeNodeTips = variableMap.get('isNeedFlowFreeNodeTips');
    }

    if(isNeedFlowFreeNodeTips && variableMap.has('wflinkTipOkCount')) {
        isNeedFlowFreeNodeTips = variableMap.get('wflinkTipOkCount') == 0;
    }
    return isNeedFlowFreeNodeTips;
}